﻿using System;
using System.Collections.Generic;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using System.Windows.Media.Media3D;

namespace ZOIL.Library.Behaviors
{
    [Obsolete("Legacy selection behavior", false)]
    public class ZLandscapeSelectionBehavior : FrameworkElement
    {
        #region Public Properties

        public ContentControl TargetControl;

        #endregion

        #region Private Properties

        private bool _select;

        #endregion

        #region Public Events

        public delegate void SelectionCancelledEventHandler(object sender, ZLandscapeSelectionFinishedEventArgs e);

        public delegate void SelectionChangedEventHandler(object sender, ZLandscapeSelectionEventArgs e);

        public delegate void SelectionFinishedEventHandler(object sender, ZLandscapeSelectionFinishedEventArgs e);

        public delegate void SelectionStartedEventHandler(object sender, ZLandscapeSelectionEventArgs e);

        public static readonly RoutedEvent SelectionFinishedEvent = EventManager.RegisterRoutedEvent("SelectionFinished", RoutingStrategy.Bubble,
                                                                                                     typeof (SelectionFinishedEventHandler),
                                                                                                     typeof (ZLandscapeSelectionBehavior));

        public static readonly RoutedEvent SelectionStartedEvent = EventManager.RegisterRoutedEvent("SelectionStarted", RoutingStrategy.Bubble,
                                                                                                    typeof (SelectionStartedEventHandler),
                                                                                                    typeof (ZLandscapeSelectionBehavior));

        public static readonly RoutedEvent SelectionChangedEvent = EventManager.RegisterRoutedEvent("SelectionChanged", RoutingStrategy.Bubble,
                                                                                                    typeof (SelectionChangedEventHandler),
                                                                                                    typeof (ZLandscapeSelectionBehavior));

        public static readonly RoutedEvent SelectionCancelledEvent = EventManager.RegisterRoutedEvent("SelectionCancelled", RoutingStrategy.Bubble,
                                                                                                      typeof (SelectionCancelledEventHandler),
                                                                                                      typeof (ZLandscapeSelectionBehavior));

        public event SelectionFinishedEventHandler SelectionFinished
        {
            add { AddHandler(SelectionFinishedEvent, value); }
            remove { RemoveHandler(SelectionFinishedEvent, value); }
        }

        public event SelectionStartedEventHandler SelectionStarted
        {
            add { AddHandler(SelectionStartedEvent, value); }
            remove { RemoveHandler(SelectionStartedEvent, value); }
        }

        public event SelectionChangedEventHandler SelectionChanged
        {
            add { AddHandler(SelectionChangedEvent, value); }
            remove { RemoveHandler(SelectionChangedEvent, value); }
        }

        public event SelectionCancelledEventHandler SelectionCancelled
        {
            add { AddHandler(SelectionCancelledEvent, value); }
            remove { RemoveHandler(SelectionCancelledEvent, value); }
        }

        public void RaiseSelectionStartedEvent(Point p)
        {
            _select = true;
            var args = new ZLandscapeSelectionEventArgs(SelectionStartedEvent, p);
            args.Source = this;
            RaiseEvent(args);
            TargetControl.RaiseEvent(args);
        }

        public void RaiseSelectionChangedEvent(Point p)
        {
            if (_select)
            {
                var args = new ZLandscapeSelectionEventArgs(SelectionChangedEvent, p);
                args.Source = this;
                RaiseEvent(args);
                TargetControl.RaiseEvent(args);
            }
        }

        public void RaiseSelectionFinishedEvent()
        {
            if (_select)
            {
                var args = new ZLandscapeSelectionFinishedEventArgs(SelectionFinishedEvent);
                args.Source = this;
                RaiseEvent(args);
                try
                {
                    TargetControl.RaiseEvent(args);
                }
                catch (Exception e)
                {
                    MessageBox.Show(e.Message);
                }
                _select = false;
            }
        }

        public void RaiseSelectionCancelledEvent()
        {
            if (_select)
            {
                var args = new ZLandscapeSelectionFinishedEventArgs(SelectionCancelledEvent);
                args.Source = this;
                RaiseEvent(args);
                TargetControl.RaiseEvent(args);
                _select = false;
            }
        }

        #endregion

        #region Construct

        public ZLandscapeSelectionBehavior(ContentControl target)
        {
            TargetControl = target;
        }

        #endregion

        #region Treehelper

        private static readonly List<DependencyObject> results = new List<DependencyObject>();
        private static Type hitTestType = typeof (DependencyObject);

        /// <summary>
        ///     Gets the visual root of visual tree, by climbing up visual and logical tree
        /// </summary>
        /// <param name="initial">Object where search begins</param>
        /// <returns>found object</returns>
        public DependencyObject FindVisualTreeRoot(DependencyObject initial)
        {
            DependencyObject current = initial;
            DependencyObject result = initial;

            while (current != null)
            {
                result = current;
                if (current is Visual || current is Visual3D)
                {
                    current = VisualTreeHelper.GetParent(current);
                }
                else
                {
                    current = LogicalTreeHelper.GetParent(current);
                }
            }

            return result;
        }

        /// <summary>
        ///     Hittest for Elements in Geometryobject
        /// </summary>
        /// <param name="geo"></param>
        /// <param name="reference"></param>
        /// <returns>returns matched Elements of Hittest</returns>
        public static List<DependencyObject> GetElementsInGeometry(Geometry geo, UIElement reference, Type objectType)
        {
            results.Clear();
            hitTestType = objectType;
            VisualTreeHelper.HitTest(reference,
                                     MyHitTestFilter,
                                     HitTestResult,
                                     new GeometryHitTestParameters(geo));

            return results;
        }

        // Return the result of the hit test to the callback.
        public static HitTestResultBehavior HitTestResult(HitTestResult result)
        {
            // Add the hit test result to the list.
            results.Add(result.VisualHit);

            // Set the behavior to return visuals at all z-order levels.
            return HitTestResultBehavior.Continue;
        }

        public static HitTestFilterBehavior MyHitTestFilter(DependencyObject o)
        {
            // Test for the object value you want to filter.
            if (o.GetType() != hitTestType)
            {
                // Visual object and descendants are NOT part of hit test results enumeration.
                return HitTestFilterBehavior.ContinueSkipSelf;
            }
            else
            {
                results.Add(o);
                // Visual object is part of hit test results enumeration.
                return HitTestFilterBehavior.Continue;
            }
        }

        #endregion
    }
}